<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="formIs"
      class="bg-bg_color w-[99/100] pl-8 pt-4"
    >
      <el-form-item label="姓名：" prop="name">
        <el-input
          v-model="formIs.name"
          placeholder="请输入姓名"
          clearable
          class="!w-[180px]"
          @change="getList()"
        />
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input
          v-model="formIs.phone"
          placeholder="请输入手机号"
          clearable
          maxlength="11"
          @change="getList"
          class="!w-[180px]"
          @input="formIs.phone = formIs.phone.replace(/[^\d]/g, '')"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch(formIs)"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="贷款管理员" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="addLoanAdmin"
        >
          添加贷款管理员
        </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table
          border
          ref="waterRef"
          :row-key="formIs.role_id"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="columns"
          :checkList="checkList"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleEditLoan(row)"
            >
              修改
            </el-button>
            <el-popconfirm title="是否确认删除?" @confirm="handleDelete(row)">
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <addLoadEdit
      ref="addLoadEditRef"
      :titleInfo="titleInfo"
      @handleSubmit="handleSubmit"
      :isEdit="isEdit"
    />
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, inject, onMounted, nextTick } from "vue";
import { useRole } from "./hook";
import type { ElTreeV2 } from "element-plus";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { getRoleList, getRoleUpdate } from "@/api/user";
import { message } from "@/utils/message";
import * as CryptoJS from "crypto-js";
import { transformI18n } from "@/plugins/i18n";
import { storageSession } from "@pureadmin/utils";
import { getSessionKey } from "@/utils/auth";
import {
  getAsyncAllRoutes,
  updateAsyncRoutes,
  roleList,
  addRoleInsert,
  updateRole,
  roleAssign
} from "@/api/routes";
import { getRoleInfo } from "@/api/user";
import { useUserStoreHook } from "@/store/modules/user";
import type { TreeNode } from "element-plus/es/components/tree-v2/src/types";
// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
// import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { getList } from "../../../api/loanInfo";
import { getAdminManageList } from "@/api/loanInfo";
import addLoadEdit from "./components/addLoadEdit.vue";
import { staffInsert, staffUpdate } from "@/api/loanAdminPage";
defineOptions({
  name: "Administrators"
});
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
interface treeNode extends TreeNode {
  meta: {
    title: string;
  };
}
interface FormType {
  role_name: string;
  role_desc: string;
  role_id: string;
}
const addLoadEditRef = ref("");
const isEdit = ref(0);
const refresh: any = inject("reload");
const dialogFormVisible = ref(false);
const formRef = ref();
const menus = ref([]);
const adminId = ref(false);
const waterRef = ref();
const dialogRoute = ref(false);
const formLabelWidth = "100px";
const roleId = ref("");
const roleName = ref("");
const checkedKeys = ref([]);
const titleInfo = ref("");
const formIs = reactive<FormType>({
  name: "",
  phone: ""
});
const dataProps = ref({
  value: "route_id",
  children: "children",
  label: "title"
});
const formIsRef = ref({});
const {
  loading,
  columns,
  dataList,
  pagination,
  // buttonClass,
  onSearch,
  resetForm,
  // handleUpdate,
  handleDelete,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  getList
} = useRole(waterRef);

//获取角色列表
async function handleUserList(roleId) {
  const role = {
    role: roleId
  };

  const roleJson = JSON.stringify(role);
  const roleBase64 = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(roleJson)
  );
  const roleValue = {
    value: roleBase64
  };
  const res = await getRoleList(roleValue);
  if (res.code === 200) {
    message(res.msg, { type: "success" });
  } else {
    message(res.msg, { type: "error" });
  }
}
const handleInput = value => {
  // 使用正则表达式匹配只有字母和数字的字符串
  const regex = /^[a-zA-Z0-9]+$/;
  if (!regex.test(value)) {
    // 如果输入的值不符合正则表达式，则将inputValue重置为上一个合法的值
    formIs.role_name = value.replace(/[^a-zA-Z0-9]/g, "");
  }
};

// 添加贷款管理员
const addLoanAdmin = () => {
  isEdit.value = 0;
  titleInfo.value = "贷款管理员添加";
  addLoadEditRef.value.opneDialogVisible();
};
// 修改贷款管理员
const handleEditLoan = row => {
  const rowData = { ...row };
  isEdit.value = 1;
  titleInfo.value = "贷款管理员修改";
  nextTick(() => {
    addLoadEditRef.value.opneDialogVisible(rowData);
  });
};
//新增/修改角色
const handleSubmit = params => {
  delete params.update_time;
  delete params.create_time;
  if (isEdit.value == 0) {
    staffInsert(params).then(res => {
      if (res.code == 200) {
        message(res.msg, { type: "success" });
        nextTick(() => {
          addLoadEditRef.value.closeDialogFormVisible();
          getList();
        });
      } else {
        message(res.msg, { type: "error" });
      }
    });
  } else {
    staffUpdate(params).then(res => {
      if (res.code == 200) {
        message(res.msg, { type: "success" });
        nextTick(() => {
          addLoadEditRef.value.closeDialogFormVisible();
          getList();
        });
      } else {
        message(res.msg, { type: "error" });
      }
    });
  }
};

const getListData = async () => {
  const params = {
    pagesize: 1,
    page: 10,
    company_name: "",
    legal_name: "",
    admin_nick: ""
  };
  const res = await getAdminManageList(params);
  if (res.code === 200) {
    dataList.value = res.data.data;
    pagination.total = res.data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  } else {
    message(res.msg, { type: "error" });
  }
};
</script>
<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
